const express = require('express')
const app = express()
const port = 3000
const fs = require('fs')
const XiaoAi = require('xiaoai-tts')
var _ = require('lodash');

let client = null
let preSays = []

// 尝试读取本地存储的小爱session
const Session = fs.readFileSync('./xiaoai/session.json', {
	encoding: 'utf8'
})
/**
 * 登录，实例化小爱
 */
if (Object.keys(JSON.parse(Session)).length > 0) {
	//通过session登录
	console.log(Object.keys(JSON.parse(Session)).length);
	client = new XiaoAi(JSON.parse(Session))
	console.log("通过session登录");
} else {
	//通过用户密码登录
	client = new XiaoAi('13809926493', '123456')
	client.connect().then(function(Session) {
		let session = JSON.stringify(Session);
		console.log("session:" + session);
		fs.writeFileSync('./xiaoai/session.json', session)
		console.log("通过用户密码登录，并存储Session");
	})
}



// 导入WebSocket模块:
const WebSocket = require('ws');
// 引用Server类:
const WebSocketServer = WebSocket.Server;
// 实例化:
var wss = new WebSocketServer({
	port: 3001
});
wss.on('connection', function (ws) {
	console.log(`ws 已经连接上`);
	ws.on('message', function (message) {
		preSays.push(message);
		console.log(`收到客户端的数据: ${message}`);
	})
});



var checkStatus = function () {
	setInterval(function () {
		client.getStatus().then(function (res) {
			if(res.status!==1){
				if (preSays.length>0){
					console.log("还有"+preSays.length+"句话要说")
					client.say(preSays[0]).then(function () {
						console.log("说完了")
					}).catch(function () {
						console.log("说废了")
					}).finally(function(){
						preSays = _.drop(preSays);
					});
				}else{
					console.log("没话说了啊")
				}
			}else {
				console.log("话还没说完呢  等一会儿")
			}
			console.log(res.status)
		})
	},1000)
}
checkStatus();

app.get('/', (req, res) => res.send('Hello World!'))
app.get('/say', function(req, res) {
	let words = req.param('wd')
	console.log(words)
	 client.say(words).then(function() {
		console.log("让小爱同学说:" + words);
	}).catch(function() {
		console.log("说话失败了");
	});
})


app.listen(port, () => console.log(`Example app listening on port ${port}!`))
